package com.gang.music.system.controller;

import com.gang.music.common.AjaxResult;
import com.gang.music.core.annotation.Permission;
import com.gang.music.core.constant.Cst;
import com.gang.music.core.file.BladeFile;
import com.gang.music.system.entity.Song;
import com.gang.music.system.service.SongService;
import com.google.common.collect.Maps;
import com.smallchill.core.toolbox.Func;
import com.smallchill.core.toolbox.file.BladeFileKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Controller
@RequestMapping("/system/song")
public class SongAdminController extends BaseController {
	
	@Autowired
	private SongService songService;

	@Permission({"song:list"})
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public String getSongList(Map<String, Object> map) {
		
		map.put("songList", songService.findAllWithInfo());
		return "admin/song/songList";
	}
	
	/**
	 * 删除歌曲
	 */
	@Permission({"song:delete"})
	@ResponseBody
	@RequestMapping("/delete/{id}")
	public AjaxResult deleteSong(@PathVariable("id") Long id) {
		try {
			songService.deleteById(id);
			return success();
		} catch (Exception e) {
			e.printStackTrace();
			return error("系统出错");
		}
	}
	/**
	 * 添加歌曲页面
	 * @return
	 */
	@Permission({"song:add"})
	@RequestMapping(value="/add", method=RequestMethod.GET)
	public String addSong() {
		
		return "admin/song/songInput";
	}

	/**
	 * 修改歌曲页面,与添加歌曲同一个页面
	 */
	@Permission({"song:update"})
	@RequestMapping("/update/{id}")
	public String editSong(@PathVariable Long id, Map<String, Object> map) {
		
		map.put("song", songService.selectById(id));
		return "admin/song/songInput";
	}
	
	/**
	 * 添加或修改歌曲
	 */
	@Permission({"song:add"})
	@ResponseBody
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public AjaxResult saveOrUpdate(Song song) {
		
		if (songService.saveOrUpdate(song)) {
			
			return success();
		}
		return error();
	}
	/**
	 * 
	 * 通过文件名截取歌手,歌名,
	 * 并返回前台回显
	 */
	@Permission({"song:add"})
	@ResponseBody
	@RequestMapping("/convert")
	public Map<String, String> convertSong(String fileName) {
		
		Map<String, String> songMap = Maps.newHashMap();
		if(fileName.indexOf("-")!=-1) {
			fileName = fileName.replaceAll(" ", "");
			String singer = fileName.substring(0, fileName.indexOf("-"));
			String songName = 
					fileName.substring(fileName.indexOf("-")+1, fileName.indexOf("."));
			songMap.put("songName", songName);
			songMap.put("singer", singer);
		}
		return songMap;
	}

	/**
	 * 上传音乐文件
	 * @throws Exception 
	 */
	@Permission({"song:add"})
	@ResponseBody
	@RequestMapping("/upload/mp3")
	public AjaxResult uploadMp3(MultipartFile songFile){
		
		if(!songFile.isEmpty()) {
			String originalFileName = songFile.getOriginalFilename();
			boolean ok = BladeFileKit.testExt("media", originalFileName);
			if(!ok) {
				return error("不支持该文件类型");
			}
		}else {
			return error("请选择要上传的歌曲");
		}
		BladeFile bladeFile = BladeFile.getFile(songFile, "/media");
		bladeFile.transfer();
		
		return success();
	}
	/**
	 * 上传图片
	 * */
	@Permission({"song:add"})
	@ResponseBody
	@RequestMapping("/upload/img")
	public AjaxResult uploadIMG(MultipartFile imgFile){
		
		if(!imgFile.isEmpty() ) {
			String originalFileName = imgFile.getOriginalFilename();
			boolean ok = BladeFileKit.testExt("image", originalFileName);
			if(!ok) {
				return error("不支持该图片类型");
			}
		}else{
			return error("请选择要上传的图片");
		}
		BladeFile bladeFile = BladeFile.getFile(imgFile, "/image");
		bladeFile.transfer();
		
		return success();
	}
	
	/**
	 * 上传歌词
	 * */
	@Permission({"song:add"})
	@ResponseBody
	@RequestMapping("/upload/lyr")
	public AjaxResult uploadLyr(MultipartFile lyrFile){
		
		if(!lyrFile.isEmpty()) {
			String originalFileName = lyrFile.getOriginalFilename();
			String extName = BladeFileKit.getFileExt(originalFileName);
			boolean ok = ".lrc".equals(extName);
			if(!ok) {
				return error("只能选择lrc格式的歌词");
			}
		}else{
			return error("请选择要上传的歌词文件");
		}
		BladeFile bladeFile = BladeFile.getFile(lyrFile, "/lyric");
		bladeFile.transfer();
		
		return success();
	}
	
	/**
	 * 返回歌手图片,使用通配符,否则"."后面的文件扩展名获取不到
	 */
	@Permission({"song:renderFile"})
	@RequestMapping("/renderFile/{imgName:.+}")
	public void renderFile(HttpServletRequest request, 
			HttpServletResponse response, @PathVariable String imgName) {
		
		OutputStream out = null;
		try {
			InputStream inputStream = new FileInputStream(Cst.me().getUploadRealPath() + "/image/" + imgName);
			byte[] fileDate = FileCopyUtils.copyToByteArray(inputStream);
			response.setContentType("image/png");
			out = response.getOutputStream();
			out.write(fileDate);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@ModelAttribute
	public void getSong(@RequestParam(value="id", required=false) Long id,
			Map<String, Object> map) {
		
		if(!Func.isEmpty(id)) 
			map.put("song", songService.selectById(id));
	}
}
